var baseUrl = "http://feeds.createcloud.cn/api";
var app = angular.module('weitheme', ['mobile-angular-ui', 'ui.router', 'ngAnimate', 'ngSanitize', 'LocalStorageModule']);

app.config(function($stateProvider, $urlRouterProvider, $locationProvider, $uiViewScrollProvider) {
    // $locationProvider.html5Mode(true); 

    // $uiViewScrollProvider.useAnchorScroll();
    // For any unmatched url, redirect to /state1
    $urlRouterProvider.otherwise("/list");

    // Now set up the states
    $stateProvider
        .state('setChannels', {
            url: "/setting/channels",
            templateUrl: 'templates/setting.channels.html',
            controller: 'setting.channels.ctrl'
        })
        .state('list', {
            url: "/list/:type/:channel/:cate",
            templateUrl: function($stateParams){
                // noted that $stateParams is not an injected argument
                return 'templates/' + $stateParams.type + '.list.html';
            },
            controllerProvider: ['$stateParams', function($stateParams){
                // return $stateParams.type + '.list.ctrl';
                return 'entity.list.ctrl';
            }],
            resolve: {
                feed: ['$http', '$stateParams', function($http, $stateParams){
                    var url = baseUrl + '/' + $stateParams.type,
                        config = {
                            params: {
                                // items_per_page: 5,
                                channel: $stateParams.channel,
                                category: $stateParams.cate,
                                page: 0
                            }
                        };
                    return $http.get(url, config).then(function(response) {
                        return response.data;
                    });
                }]
            }
        })
        .state('details', {
            url: "/:type/:id.php",
            templateUrl: function($stateParams) {
                return "templates/" + $stateParams.type + ".details.html";
            },
            controller: "entity.details.ctrl",
            resolve: {
                entity: ['$http', '$stateParams',
                    function($http, $stateParams) {

                        var url = baseUrl + '/' + $stateParams.type + '/' + $stateParams.id;

                        return $http.get(url).then(function(response) {
                            return response.data[0];
                        });
                    }
                ]
            }
        });
});

app.config(['$provide', function($provide){
        $provide.decorator('$rootScope', ['$delegate', function($delegate){

            Object.defineProperty($delegate.constructor.prototype, '$onRootScope', {
                value: function(name, listener){
                    var unsubscribe = $delegate.$on(name, listener);
                    this.$on('$destroy', unsubscribe);

                    return unsubscribe;
                },
                enumerable: false
            });


            return $delegate;
        }]);
    }]);

app.run(function($rootScope, $state, $stateParams, $urlRouter, Channels) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

    $rootScope.$on('$stateChangeStart', function(event) {
        $rootScope.toggle('page-loading', 'on');
    });
    $rootScope.$on('$viewContentLoaded', function(event) {
        $rootScope.toggle('page-loading', 'off');
    });

    // init channels data
    if (Channels.list.length == 0) {
        Channels.init().then(function(data){
            Channels.list = data;
            $rootScope.$emit('channelsUpdated');
        });
    };

});

app.factory('Utils', ['$q',
    function($q) {
        return {
            isImage: function(src) {

                var deferred = $q.defer();

                var image = new Image();
                image.onerror = function() {
                    deferred.resolve(false);
                };
                image.onload = function() {
                    deferred.resolve(true);
                };
                image.src = src;

                return deferred.promise;
            }
        };
    }
]);

app.service('Channels', ['$http', '$q', 'localStorageService', function($http, $q, localStorageService){

    // 设置channel更新时间，对比后随时刷新
    // localStorageService.clearAll();

    // init 
    /*var channels = localStorageService.get('Channels');
    if (channels == null) {        // 读取api接口
        var defer = $q.defer();
        $http.get(baseUrl + '/category').then(function(response){
            // channels = data;
            localStorageService.set('Channels', channels);

            defer.resolve(response.data);
        });
        
        return defer.promise;
    };*/
    // init 
    var channels = (function(){
        var tmp = localStorageService.get('Channels');
        if (tmp == null) {        // 读取api接口
            var defer = $q.defer();
            $http.get(baseUrl + '/category').then(function(response){
                // channels = data;
                localStorageService.set('Channels', response.data);

                // defer.resolve(response.data);
                return response.data;
            });
            
            // return defer.promise;
        }else {
            return tmp;
        }
    })();

    var instance = {
        list: [],
        init: function() {
            var defer = $q.defer();
            
            var localS = localStorageService.get('Channels');

            if (localS == null) { // 读取api接口
                // var defer = $q.defer();
                $http.get(baseUrl + '/category').success(function(response){
                    this.list = response;
                    localStorageService.set('Channels', response);
                    defer.resolve(response);
                });

                
            } else {
                this.list = localS;
                defer.resolve(this.list);
            }

            return defer.promise;
        },
        update: function() {},
        flavor: function(index) {
            this.list[index].flavored = true;
            this.updateLocalStorage();
        },
        unflavor: function(index) {
            this.list[index].flavored = false;
            this.updateLocalStorage();
        },
        updateLocalStorage: function() {
            localStorageService.set('Channels', this.list);
        }
    };

    return instance;
    

}]);

app.service('CachedFeeds', ['localStorageService', function(localStorageService){

    var set = function(key, value) {
        localStorageService.set(key, value);
    }

    var get = function(key) {
        localStorageService.get(key);
    }

    return {};
}])

app.controller('setting.channels.ctrl', ['$scope', '$rootScope', 'Channels', function($scope, $rootScope, Channels){

    $scope.channels = Channels.list;

    $scope.flavor = function(index) {
        Channels.flavor(index);
    }
    $scope.unflavor = function(index) {
        Channels.unflavor(index);
    }

    $scope.$onRootScope('channelsUpdated', function(){
        $scope.channels = Channels.list;
    });
}])

app.controller('nav.ctrl', ['$scope', '$http', '$state', 'Channels',
    function($scope, $http, $state, Channels) {

        $scope.menus = Channels.list ;

        $scope.$onRootScope('channelsUpdated', function(){
            $scope.menus = Channels.list;
        });

    }
]);
app.controller('entity.list.ctrl', ['$scope', '$http', 'feed', '$stateParams', '$location',
    function($scope, $http, feed, $stateParams, $location) {

        $scope.list = feed;
        $scope.currentPage = 1;
        $scope.loadBtnLabel = '加载更多';

        $scope.loadMore = function() {
            $scope.loadBtnLabel = '<i class="fa fa-refresh fa-spin"></i>';
            var url = baseUrl + '/' + $stateParams.type,
                config = {
                    params: {
                        channel: $stateParams.channel,
                        category: $stateParams.cate,
                        page: $scope.currentPage
                    }
                };
            $http.get(url, config).success(function(data) {
                if (data.length > 0) {
                    $scope.list = $scope.list.concat(data);
                    $scope.currentPage++;
                    $scope.loadBtnLabel = '加载更多';
                } else {
                    $scope.loadBtnLabel = '无更多数据';
                }
            });

            // $location.hash('bottom');
            // $anchorScroll();
        }
    }
]);
app.controller('entity.details.ctrl', ['$scope', 'entity',
    function($scope, entity) {

        $scope.entity = entity;

    }
]);